const { getProperty , each } = require('../../lib/tools')
const { readdirSync,writeFileSync } = require('fs')
const { join , sep } = require('path')
const addField = require('./libs/addField')
const addSetAndGet = require('./libs/addSetAndGet')
const { readYaml,writeYaml } = require('../../lib/files')
const { assert } = require('../../lib/tools')
const { getNewDist } = require('../tools')

/**
 * 生成实体类
 * @param {*} param0 
 * @returns 
 */
module.exports = function({config:{globeConfig,inits},writeOutTheArea}){
    
    const entryDir = getProperty(globeConfig,g=>g.globe.dist.globe.step1,undefined)
    const files = getProperty(entryDir,d=>readdirSync(d),undefined)
    const distDir = getProperty(globeConfig, g=>g.globe.dist.backend.classes.entry)
    assert(distDir,"实体类的类配置目标目录不能为空!")

    if(!files){
        console.log(`entry generate fail. the files is null...`)
        return
    }

    files.forEach(f=>{
        const entryInfo = getProperty(entryDir,d=> readYaml(join(d,f)))
        const entry = getTemplate(inits.entryTemplate)
        entry.name = getProperty(entryInfo,info=>info.base.entryClassName)
        entry.description = getProperty(entryInfo,info=>info.base.entryComment,"")
        assert(entry.name,"实体类类名不能为空!")
        if(entryInfo && entryInfo.fields){
            each(entryInfo.fields, field=>{
                addField(entry,field)
                addSetAndGet(entry,field)
            })
        }
        const package = getProperty(entryInfo,en=>en.base.entryPackage)
        assert(package,"控制器Package不能为空!")

        const distPath = getProperty(entryInfo,en=>en.base.distPath)
        assert(distPath,"distPath不能为空!")

        entry.package = package

        entry.dist = getNewDist(distPath,package,entry.name+".java")
        const outPath = join(distDir,f)
        entry.imports = [...entry.imports]
        writeYaml(outPath,entry)
        entry.format = 'java'
        writeOutTheArea.push(entry)
    })
    

}

function getTemplate(template){
    const result = JSON.parse(JSON.stringify(template))
    // result.imports = []
    result.imports = new Set()
    result.fields = []
    return result
}

